#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: 李吉凯
@Email: lijk34925@hundsun.com
@Time: 2021/7/19 15:48
@File: dataoperation.py
"""
import os

import pandas as pd
import yaml
# from pprint import pprint
from BladeFerm.Lib.Common import logger


class YamlOperation:
    def __init__(self, filepath):
        self.filepath = filepath

    def readYaml(self):
        if os.path.exists(self.filepath):
            with open(self.filepath, 'r', encoding='utf-8') as f:
                cons = yaml.safe_load(f.read())
        else:
            cons = {}
        return cons

    def writeYaml(self, contents):
        with open(self.filepath, "w", encoding="utf-8") as f:
            yaml.dump(contents, f, allow_unicode=True)
        return True

    def updateCookies(self, rawData, username, datalist):
        '''
        funtion: 更新rawData中的值，数据结构 rawData={ip:{name:[{},{}]}}
        :param rawData: dict1 以url_ip为键，dict2为值的字典项
        :param username: dict2 以username为键，datalist为值的字典项
        :param datalist: list 要更新的cookies信息
        :return:
        '''
        new_dic = {username: datalist}
        target_ip = datalist[0]['domain']
        tempdic = {'cur_url_ip': target_ip, 'cur_test_user': username}
        rawData.update(tempdic)
        if target_ip in rawData:
            target_datas = rawData[target_ip]
            target_datas.update(new_dic)
        else:
            new_dic2 = {target_ip: new_dic}
            rawData.update(new_dic2)
        return rawData


class UpdateCookies:
    @classmethod
    def saveCookies(cls, filepath, username, cookiesList):
        ymobj = YamlOperation(filepath)
        rawdata = ymobj.readYaml()
        newdata = ymobj.updateCookies(rawdata, username, cookiesList)
        ymobj.writeYaml(newdata)
        return newdata

    @classmethod
    def getCookies(cls, filepath, name=None):
        cookie = []
        ymobj = YamlOperation(filepath)
        rawdata = ymobj.readYaml()
        targetIP = rawdata['cur_url_ip']
        username = rawdata['cur_test_user']
        if name is not None:
            username = name
        if targetIP in rawdata:
            if username in rawdata[targetIP]:
                cookie = rawdata[targetIP][username]
        return cookie


class YamlData:
    def __init__(self, filename):
        self._read_yaml(filename)
        self.res_list = []

    def _read_yaml(self, filename):
        '''
        读取yaml中的原始数据
        :param filename:
        :return:
        '''
        self.filename = filename
        self.fp, self.fn = os.path.split(filename)
        YOP = YamlOperation(filename)
        raw = YOP.readYaml()
        logger.info(f'{self.fn} test raw data : {raw}')
        self.input_data = raw.get('input_data', [None])
        self.expect_data = raw.get('ui_expect', [None])

    def input_data_to_dict(self, input_data_list):
        '''
        输入的列表数据转化成字典类型
        :param input_data_list:
        :return:
        '''
        input_dict = dict()
        for unit in input_data_list:
            for key_first, value_first in unit.items():
                cur_values = input_dict.get(key_first, [])
                cur_values.append(value_first)
                input_dict.update({key_first: cur_values})
        logger.info(f'input_dic: {input_dict}')
        return input_dict

    def split_input_data(self, input_dict):
        '''
        字典数据合并
        :param input_dict:
        :return:
        '''
        index = 0
        cur_dict = dict()
        for f_key, f_value in input_dict.items():
            value_tp = f_value[0]
            if isinstance(value_tp, dict):
                add_key = f'{f_key}(Object)'
                add_value_len = len(f_value)
                index = index + 1
                add_value = [f'sheet{index}|' + str(i+1) for i in range(add_value_len)]
                sec_data_list = f_value
                sec_cur_dic = self._union_input_data(sec_data_list)
                logger.info(f'index: {index, sec_cur_dic}')
                self.res_list.append(sec_cur_dic)
            elif isinstance(value_tp, int):
                add_key = f'{f_key}(Number)'
                add_value = f_value
            elif isinstance(value_tp, list):
                add_key = f'{f_key}(ArrayNoKey)'
                add_value = f_value
            else:
                # 其余都是按照str类型去处理
                add_key = f_key
                add_value = f_value
            cur_dict[add_key] = add_value
        self.res_list.insert(0, cur_dict)
        logger.info(f'last res_list: {self.res_list}')
        return self.res_list


    def _union_input_data(self, data_list):
        input_dict = self.input_data_to_dict(data_list)
        cur_dict = dict()
        for f_key, f_value in input_dict.items():
            value_tp = f_value[0]
            if isinstance(value_tp, int):
                add_key = f'{f_key}(Number)'
                add_value = f_value
            elif isinstance(value_tp, list):
                add_key = f'{f_key}(ArrayNoKey)'
                add_value = f_value
            else:
                # 其余都是按照str类型去处理
                add_key = f_key
                add_value = f_value
            cur_dict[add_key] = add_value
        logger.info(f'union_cur_dict: {cur_dict}')
        return cur_dict

    def data_to_excel(self, data_list=None, excel_path=None):
        '''
        数据转换成dataframe格式。并写入Excel中
        :param data_list: [{'客户类型': ['个人', '个人'], '列表数据(ArrayNoKey)': [['文本', '字典', '名著'], ['文本', '字典', '名著']],
                 '客户特性因素/可疑交易监测记录(Object)': ['sheet1|1', 'sheet1|2'], '定位数据(Object)': ['sheet2|1'],
                 '修改数据(Object)': ['sheet3|1']}, {'是否启用': ['是', '是'], '指标权重': ['12', '12']},
                {'类型名称': ['客户评级流程逾期天数设置']}, {'流程逾期：': ['10'], '是否启用：': ['是']}]
        :param excel_path: .xls格式的Excel文件的全路径
        :return:
        '''
        writer = pd.ExcelWriter(excel_path)
        for i, unit in enumerate(data_list):
            header_list = list(unit.keys())
            # 找数组最大的长度，让数据长度保持一致。方便转换成DataFrame数据
            max_len = 0
            for k, v in unit.items():
                if len(v) > max_len:
                    max_len = len(v)
            for k2, v2 in unit.items():
                sec_list = v2 + [None]*(max_len-len(v2)) if len(v2) < max_len else v2
                sec_list = [None] + sec_list if i == 0 else sec_list
                unit.update({k2: sec_list})
            res_data = pd.DataFrame(unit)
            index_list = [i+1 for i in range(max_len)]
            if i == 0:
                first_col = ['参数说明'] + index_list
                exp_list = self._expect_data_to_list()
                if len(exp_list) < max_len:
                    second_col = exp_list + [None]*(max_len-len(exp_list))
                elif len(exp_list) > max_len:
                    second_col = exp_list[:max_len]
                else:
                    second_col = exp_list
                second_col.insert(0, None)
                res_data.insert(0, '序号', first_col)
                res_data.insert(1, '期望', second_col)
                header_list.insert(0, '序号')
                header_list.insert(1, '期望')
            else:
                res_data.insert(0, 'GroupID', index_list)
                header_list.insert(0, 'GroupID')
            logger.info(f'res_data: {res_data}')
            res_data.to_excel(writer, 'sheet' + str(i), index=False, header=header_list)
        writer.save()
        return excel_path


    def _expect_data_to_list(self):
        '''
        期望数据转换成
        :return:
        '''
        self.expect_list = list()
        logger.info(f'Raw expect data: {self.expect_data}')
        for unit in self.expect_data:
            child_list = []
            for key, value in unit.items():
                cur_expect_str = f'{key}={value}'
                child_list.append(cur_expect_str)
            child_list_str = ';'.join(child_list)
            self.expect_list.append(child_list_str)
        logger.info(f'Result of expect: {self.expect_list} ',)
        return self.expect_list


if __name__ == '__main__':
    path = "E:\\Web_AutoTest\\执行机系列对外\\pythonFrame\\frame\\login_cookies.yaml"
    # fp = YamlOperation(path)
    # rData = fp.readYaml()
    # print('rdata:', rData)
    name = "mfxsh02"
    cookieinfo = [{'domain': '10.20.19.248', 'expiry': 1625033250}, {'domain': '10.20.19.248', 'secure': False}]
    # resdata = UpdateCookies.saveCookies(path, name, cookieinfo)
    resdata = UpdateCookies.getCookies(path, '10.20.19.248', 'wj')
    print(resdata)

